<template>
  <el-upload
    class="avatar-uploader"
    :show-file-list="true"
    :auto-upload="false"
    ref="upload"
    :on-change="onchange"
    limit="1"
    :before-remove="beforeremove"
    list-type="picture-card"
  >
    <img
      v-if="imgUrl"
      class="avatar"
      :src="'http://localhost:3000' + props.imgUrl"
    />
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script setup>
import { ref, defineEmits, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
const emit = defineEmits(["uploadimg"]);
const props = defineProps({
  imgUrl: "",
});
const imageUrl = ref("");
const upload = ref();
const imgUrl = ref();
imgUrl.value = props.imgUrl;
function onchange(value) {
  if (value.raw.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小超过2MB");
    console.log(upload.value.clearFiles());
  } else {
    imgUrl.value = "";
    emit("uploadimg", value.raw);
  }
}
function beforeremove() {
  emit("uploadimg", null);
}
onMounted(() => {});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;

  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>